package com.example.springboot.ytest.ytool;


import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Copyright (C), 2017-2017, 真知码
 * FileName: IpAddrUtil
 *
 * @author jphuang
 * Date:     2017/11/13 15:58
 * Description: ip工具
 */
public class IpAddrUtil {
    private static Pattern pattern = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
    private static final String[] HEADERS_TO_TRY = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
			"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
			"HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP" };

    public static String getIp(HttpServletRequest request) {
    	int i=0;
    	String ip = request.getHeader(HEADERS_TO_TRY[i]);
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			//多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            }
			return ip;
		}
		
    	for (i=1; i<HEADERS_TO_TRY.length; i++) {
    		ip = request.getHeader(HEADERS_TO_TRY[i]);
    		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
				return ip;
			}
    	}
        return request.getRemoteAddr();
    }

    public static void main(String[] args) {
        try {
            String outerIp = getOuterIp();
            String innerIp = getInnerIp();
            System.out.println("外网IP地址: " + outerIp);
            System.out.println("内外IP地址: " + innerIp);
            System.out.println("ipv4地址: " + getV4IP());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static String getV4IP() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Matcher m = pattern.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(1);
            ip = ipstr;
        }
        return ip;
    }

    private static String getOuterIp() throws IOException {
        InputStream inputStream = null;
        try {
            URL url = new URL("http://1212.ip138.com/ic.asp");
            URLConnection urlconnnection = url.openConnection();
            inputStream = urlconnnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GB2312");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer webContent = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                webContent.append(str);
            }
            int ipStart = webContent.indexOf("[") + 1;
            int ipEnd = webContent.indexOf("]");
            return webContent.substring(ipStart, ipEnd);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    private static String getInnerIp() throws IOException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        return inetAddress.getHostAddress();
    }


}
